package com.coolweather.android;

import static com.coolweather.android.contants.Constants.PROVINCE_URL;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.coolweather.android.databinding.ChooseAreaBinding;
import com.coolweather.android.db.City;
import com.coolweather.android.db.County;
import com.coolweather.android.db.Province;
import com.coolweather.android.util.HttpUtil;
import com.coolweather.android.util.Utility;

import org.jetbrains.annotations.NotNull;
import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChooseAreaFragment extends Fragment {

    public static final int LEVEL_PROVINCE = 0;
    public static final int LEVEL_CITY = 1;
    public static final int LEVEL_COUNTY = 2;
    private ProgressDialog progressDialog;
    ArrayAdapter<String> adapter;
    List<String> dataList = new ArrayList<>();
    List<Province> provinceList;
    List<City> cityList;
    List<County> countyList;
    private Province selectedProvince;


    private City selectedCity;//选中的城市信息
    public int currentLEVEL = LEVEL_PROVINCE;

    ChooseAreaBinding binding;




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = ChooseAreaBinding.inflate(inflater, container, false);

        adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, dataList);

        binding.listView.setAdapter(adapter);

        return binding.getRoot();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding=null;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        binding.listView.setOnItemClickListener((adapterView,view,position,id)->{
            if(currentLEVEL==LEVEL_PROVINCE){
                selectedProvince=provinceList.get(position);
                queryCities();
            }else if (currentLEVEL==LEVEL_CITY){
                selectedCity=cityList.get(position);
                queryCounties();
            }else if(currentLEVEL==LEVEL_COUNTY){
                County county=countyList.get(position);
                String spot=String.format("%s|%s|%s",
                        selectedProvince.getProvinceName(),
                        selectedCity.getCityName(),
                        county.getCountyName());
                String location=county.getWeatherId().substring(2);
                Log.d("test","onActivityCreated:"+spot+"|"+location);

                Intent intent=new Intent(getActivity(),WeatherActivity.class);
                intent.putExtra("spot",spot);
                intent.putExtra("location",location);
                startActivity(intent);
                getActivity().finish();
            }
        });
        binding.backButton.setOnClickListener(V->{
            if(currentLEVEL==LEVEL_COUNTY){
                queryCities();
            }else if(currentLEVEL==LEVEL_CITY){
                queryProvinces();
            }
        });
        queryProvinces();
    }







    private void queryFromServer(String Url, String type) {
//        Log.d("test",Url);
        showProgressDialog();
        HttpUtil.sendOkHttpRequest(Url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                getActivity().runOnUiThread(()->{
                    Toast.makeText(getContext(), "访问网络失败", Toast.LENGTH_SHORT).show();
                closeProgressDialog();
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                String strJson=response.body().string();
                Log.d("test","onResponse"+strJson);
                boolean result = false;
                if("province".equals(type)){
                    result= Utility.handleProvinceResponse(strJson);
                }else if ("city".equals(type)){
                    result=Utility.handleCityResponse(strJson,selectedProvince.getId());
                }else if("county".equals(type)){
                    result=Utility.handleCountyResponse(strJson,selectedCity.getId());
                }
                if(result){
                    getActivity().runOnUiThread(()->{

                        if("province".equals(type)){
                            queryProvinces();
                        }else if ("city".equals(type)){
                            queryCities();
                        }else if("county".equals(type)){
                            queryCounties();
                        }
                        closeProgressDialog();
                    });
                }else{
                    getActivity().runOnUiThread(()->{
                        Toast.makeText(getContext(), "数据解析失败", Toast.LENGTH_SHORT).show();
                        closeProgressDialog();
                    });
                }
            }
            
        });
    }

    private void closeProgressDialog() {
        if (progressDialog!=null){
            progressDialog.dismiss();
        }
    }

    private void showProgressDialog() {
        if(progressDialog==null){
            progressDialog=new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载...");
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }
    private void queryProvinces() {
        binding.titleText.setText("中国(China)");
        binding.backButton.setVisibility(View.GONE);

        provinceList = LitePal.findAll(Province.class);
        if (provinceList.size() > 0) {
            dataList.clear();
            provinceList.forEach(item -> {
                dataList.add(item.getProvinceName());
            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLEVEL = LEVEL_PROVINCE;
        } else {
            String address=PROVINCE_URL;
            queryFromServer(address, "province");
        }
    }
    private void queryCities() {
        binding.titleText.setText(selectedProvince.getProvinceName());
        binding.backButton.setVisibility(View.VISIBLE);

        cityList = LitePal.where("provinceId=?",String.valueOf(selectedProvince.getId())).find(City.class);

        if (cityList.size() > 0) {
            dataList.clear();
            for (City city:cityList){
                dataList.add(city.getCityName());
            }

            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLEVEL = LEVEL_CITY;
        } else {
            int provinceCode=selectedProvince.getProvinceCode();
            String url=PROVINCE_URL+"/"+provinceCode;
            queryFromServer(url, "city");
        }
    }
    private void queryCounties() {
        binding.titleText.setText(selectedCity.getCityName());
        binding.backButton.setVisibility(View.VISIBLE);

        countyList = LitePal.where("cityId=?",String.valueOf(selectedCity.getId())).find(County.class);

        if (countyList.size() > 0) {
            dataList.clear();
        for (County county:countyList){
            dataList.add(county.getCountyName());
        }
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLEVEL = LEVEL_COUNTY;
        } else {
            int provinceCode=selectedProvince.getProvinceCode();
            int cityCode=selectedCity.getCityCode();
            String url=PROVINCE_URL+"/"+provinceCode+"/"+cityCode;
            queryFromServer(url, "county");
        }

    }

}
